package com.coocaa.x.demo.servlets;

import com.alibaba.fastjson.JSON;
import com.coocaa.x.service.litewebserver.webserver.NanoHTTPD;
import com.coocaa.x.service.litewebserver.webserver.servlet.Servlet;
import com.coocaa.x.service.litewebserver.webserver.servlet.ServletManager;

import java.io.InputStream;

/**
 * Created by lu on 15-9-9.
 */
public class DefaultServlet extends Servlet {
    private ServletInfo info = null;

    @Override
    protected void onCreate() {

    }

    @Override
    protected void onDestroy() {

    }

    @Override
    protected NanoHTTPD.Response onServe(NanoHTTPD.IHTTPSession session) {
        String uri = session.getUri();
        if (uri.equals("/servlets")) {
            String r = JSON.toJSONString(ServletManager.getManager(mContext).getLoadedServletInfo(), true);
            return newFixedLengthResponse(r);
        }
        return newChunkedResponse(NanoHTTPD.Response.Status.OK, NanoHTTPD.MIME_HTML, getResource(session.getUri()));
    }

    @Override
    protected InputStream getResource(String uri) {
        return getResourceFromAssets(uri);
    }

    @Override
    public synchronized ServletInfo getServletInfo() {
        if (info == null) {
            info = new ServletInfo();
            info.servletName = "";
            info.vendorName = "";
            info.versionCode = 1;
            info.versionName = "1.0.0";
        }
        return info;
    }
}
